package cn.mrlong.tools.util

import java.text.SimpleDateFormat
import java.util.*

object TimeUtil {
    private const val FORMART = "yyyy-MM-dd HH:mm:ss"

    //1711164313
    fun convert(before: String?): String {
        var res = stampToDate(before)
        if (res.isEmpty()) {
            res = dateToStamp(before)
        }
        return res
    }

    private fun stampToDate(before: String?): String {
        try {
            val date: Date
            if (before.isNullOrEmpty()) {
                date = Date(System.currentTimeMillis())
            } else {
                var timestamp = before.toLong()
                if (before.length == 10) {
                    timestamp *= 1000
                }
                date = Date(timestamp)
            }
            val sdf = SimpleDateFormat(FORMART)
            return sdf.format(date)
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        }
    }

    private fun dateToStamp(s: String?): String {
        try {
            val res: String
            val simpleDateFormat = SimpleDateFormat(FORMART)
            val date = simpleDateFormat.parse(s)
            val time = date.time
            res = time.toString()
            return res
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        }
    }

}
